﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using VirtualRouterClient;
using VirtualRouterClient.VirtualRouterService;
using Wpf_VirtualRouterPlus.Classes;
using Wpf_VirtualRouterPlus.UserControls;
using WPFSharp.Globalizer;

namespace Wpf_VirtualRouterPlus.Windows
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        #region My variable
        HotspotSettings _hotspotSettings;
        PeerManager _peerManager;
        Setting _setting;

        public Setting Setting
        {
            get { return _setting; }
            set { _setting = value; }
        }
        #endregion

        #region Os variable

        private Thread threadUpdateUI;
        private WpfNotifyIcon _trayIcon;

        public WpfNotifyIcon TrayIcon
        {
            get { return _trayIcon; }
            set { _trayIcon = value; }
        }

        #endregion

        public MainWindow()
        {
            InitializeComponent();
            _initialize();
            Loaded += new RoutedEventHandler(MainWindow_Loaded);
        }

        #region My Event: window loaded
        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            _osMainWindow_Loaded();
        }


        #endregion

        #region My init region
        private void _initialize()
        {
            _initializeLanguages();
            _initializeContentControls();
        }

        private void _initializeContentControls()
        {
            _hotspotSettings = new HotspotSettings(this);
            ccHotspotSettings.Content = _hotspotSettings;

            _peerManager = new PeerManager();
            ccPeerManager.Content = _peerManager;
        }

        private void _initializeLanguages()
        {
            _setting = new Setting();
            bool result = _setting.loadSettings();
            if (!result)
            {
                MessageBox.Show("Load settings fail, restore default settings!", "Error");
            }

            _setting.applySettings();


        }
        #endregion


        #region Os method

        private void _osMainWindow_Loaded()
        {
            // This line is for testing purposes
            //panelConnections.Children.Add(new PeerDevice(new ConnectedPeer() { MacAddress = "AA-22-33-EE-EE-FF" }));

            var args = System.Environment.GetCommandLineArgs();
            var minarg = (from a in args
                          where a.ToLowerInvariant().Contains("/min")
                          select a).FirstOrDefault();
            if (!string.IsNullOrEmpty(minarg))
            {
                this.WindowState = WindowState.Minimized;
                this.ShowInTaskbar = false;
            }

            this.AddSystemMenuItems();

            this.threadUpdateUI = new Thread(new ThreadStart(this.UpdateUIThread));
            this.threadUpdateUI.Start();

            this.Closed += new EventHandler(Window1_Closed);


            // Show System Tray Icon
            var stream = Application.GetResourceStream(new Uri("icons/virtualrouterdisabled.ico", UriKind.Relative)).Stream;
            var icon = new System.Drawing.Icon(stream);
            this._trayIcon = new WpfNotifyIcon();
            this._trayIcon.Icon = icon;
            this._trayIcon.Show();

            this._trayIcon.Text = FindResource("trayIcon_Text_RouterDisable").ToString();// "Virtual Router (Disabled)";
            this._trayIcon.DoubleClick += new EventHandler(trayIcon_DoubleClick);

            var trayMenu = new System.Windows.Forms.ContextMenuStrip();
            trayMenu.Items.Add(FindResource("trayMenu_Item_ManagerRouter").ToString(), null, new EventHandler(this.TrayIcon_Menu_Manage)); //"&Manage Virtual Router..."
            trayMenu.Items.Add(new System.Windows.Forms.ToolStripSeparator());
            trayMenu.Items.Add(FindResource("trayMenu_Item_CheckUpdate").ToString(), null, new EventHandler(this.TrayIcon_Menu_Update)); //"Check for &Updates..."
            trayMenu.Items.Add(FindResource("trayMenu_Item_About").ToString(), null, new EventHandler(this.TrayIcon_Menu_About));  //"&About..."
            this._trayIcon.ContextMenuStrip = trayMenu;

            this.StateChanged += new EventHandler(WindowMain_StateChanged);

            // Update display
            _updateDisplay();
        }

        private void _updateDisplay()
        {
            _hotspotSettings.updateDisplay();
        }

        void TrayIcon_Menu_Update(object sender, EventArgs e)
        {
            CheckUpdates();
        }

        public static void CheckUpdates()
        {
            Process.Start("http://virtualrouter.codeplex.com");
        }

        void TrayIcon_Menu_About(object sender, EventArgs e)
        {
            ShowAboutBox();
        }

        void TrayIcon_Menu_Manage(object sender, EventArgs e)
        {
            this.WindowState = WindowState.Normal;
        }

        void WindowMain_StateChanged(object sender, EventArgs e)
        {
            if (this.WindowState == WindowState.Minimized)
            {
                this.ShowInTaskbar = false;
            }
            else
            {
                this.ShowInTaskbar = true;
            }
        }

        void trayIcon_DoubleClick(object sender, EventArgs e)
        {
            this.WindowState = WindowState.Normal;
        }

        private void Window1_Closed(object sender, EventArgs e)
        {
            this.threadUpdateUI.Abort();
            this._trayIcon.Hide();
            this._trayIcon.Dispose();
        }

        void UpdateUIThread()
        {
            while (true)
            {
                this.Dispatcher.Invoke(new Action(this._updateDisplay));
                Thread.Sleep(5000); // 5 Seconds
            }
        }

        void myApp_VirtualRouterServiceDisconnected(object sender, EventArgs e)
        {
            // set binding 
            lblStatus.SetResourceReference(Label.ContentProperty, "lblStatus_ServiceNotRuning");
            //lblStatus.Content = FindResource("lblStatus_ServiceNotRuning"); //"Can not manage Virtual Router. The Service is not running.";

            this._trayIcon.Text = FindResource("trayIcon_Text_Disable").ToString();//Virtual Router (Disabled)";
            _updateDisplay();
        }

        void myApp_VirtualRouterServiceConnected(object sender, EventArgs e)
        {

            //lblStatus.Content = FindResource("lblStatus_RouterCanManage");//Virtual Router can now be managed.";
            lblStatus.SetResourceReference(Label.ContentProperty, "lblStatus_RouterCanManage");


            _updateDisplay();
        }



        #region "System Menu Stuff"

        #region Win32 API Stuff

        // Define the Win32 API methods we are going to use
        [DllImport("user32.dll")]
        private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);

        [DllImport("user32.dll")]
        private static extern bool InsertMenu(IntPtr hMenu, Int32 wPosition, Int32 wFlags, Int32 wIDNewItem, string lpNewItem);

        /// Define our Constants we will use
        public const Int32 WM_SYSCOMMAND = 0x112;
        public const Int32 MF_SEPARATOR = 0x800;
        public const Int32 MF_BYPOSITION = 0x400;
        public const Int32 MF_STRING = 0x0;

        #endregion

        private const int _AboutSysMenuID = 1001;
        private const int _UpdateSysMenuID = 1002;

        private void AddSystemMenuItems()
        {
            IntPtr windowHandle = new WindowInteropHelper(this).Handle;
            IntPtr systemMenu = GetSystemMenu(windowHandle, false);

            InsertMenu(systemMenu, 5, MF_BYPOSITION | MF_SEPARATOR, 0, string.Empty);
            InsertMenu(systemMenu, 6, MF_BYPOSITION, _UpdateSysMenuID, FindResource("systemMenu_CheckUpdate").ToString());// "Check for Updates...");
            InsertMenu(systemMenu, 7, MF_BYPOSITION, _AboutSysMenuID, FindResource("systemMenu_About").ToString());//"About...");

            HwndSource source = HwndSource.FromHwnd(windowHandle);
            source.AddHook(new HwndSourceHook(WndProc));
        }

        private static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            // Check if a System Command has been executed
            if (msg == WM_SYSCOMMAND)
            {
                // Execute the appropriate code for the System Menu item that was clicked
                switch (wParam.ToInt32())
                {
                    case _AboutSysMenuID:
                        ShowAboutBox();
                        handled = true;
                        break;
                    case _UpdateSysMenuID:
                        CheckUpdates();
                        handled = true;
                        break;
                }
            }

            return IntPtr.Zero;
        }

        #endregion

        public static void ShowAboutBox()
        {
            System.Windows.MessageBox.Show(
                            AssemblyAttributes.AssemblyProduct + " " + AssemblyAttributes.AssemblyVersion + Environment.NewLine
                            + Environment.NewLine + AssemblyAttributes.AssemblyDescription + Environment.NewLine
                            + Environment.NewLine + App.Current.FindResource("aboutBox_LicensedInfo") + Environment.NewLine //"Licensed under the Microsoft Public License (Ms-PL)"
                            + Environment.NewLine + AssemblyAttributes.AssemblyCopyright + Environment.NewLine
                            + Environment.NewLine + "http://sourceforge.net/projects/virtualrouterpl/"

                            , App.Current.FindResource("aboutBox_About").ToString()); //"About "
        }







        #endregion


        internal void setStatus(string strMessage)
        {
            //"Virtual Router Could Not Be Started!":
            //Virtual Router Started..."
            switch (strMessage)
            {

                case "Virtual Router Could Not Be Started!":
                    lblStatus.SetResourceReference(Label.ContentProperty, "lblStatus_RouterCouldNotStart");
                    txtbStatus.SetResourceReference(TextBox.TextProperty, "lblStatus_RouterCouldNotStart");
                    break;
                case "Virtual Router Started...":
                    lblStatus.SetResourceReference(Label.ContentProperty, "lblStatus_RouterStarted");
                    txtbStatus.SetResourceReference(TextBox.TextProperty, "txtbStartedStatus");
                    break;
                case "Virtual Router Stopped...":
                    lblStatus.SetResourceReference(Label.ContentProperty, "lblStatus_RouterStopped");
                    txtbStatus.SetResourceReference(TextBox.TextProperty, "txtbStoppedStatus");
                    break;
                default:
                    lblStatus.SetResourceReference(Label.ContentProperty, "lblStatus_Error");
                    txtbStatus.SetResourceReference(TextBox.TextProperty, "lblStatus_Error");
                    break;
            }
        }

        internal void callBack_UpdatePeers()
        {
            _peerManager.callBack_UpdatePeers();
        }
    }
}
